import './App.css';
import { useState, useEffect } from 'react'
import axios from "axios"
import Cache from './Cache'
const cache = new Cache(5)
// const cacheRef = useRef(new Cache(5))
function App() {

  const [data, setData] = useState([])
  const [count, setCount] = useState(30)
  const [page, setPage] = useState(1)
  const [totalCount, setTotalCount] = useState(0)

  useEffect(() => {

    function get() {
      let url = `https://api.github.com/search/repositories?q=react&page=${page}`
      axios.get(url).then(res => {
        cache.add(page, res.data.items)
        setTotalCount(res.data.total_count)
      })
    }

    if (data.length === 0 || !cache.get(page)) {
      get()
    }

    if (cache.has(page)) setData(cache.get(page))

  }, [page])

  return (
    < div >
      <ul>
        <li>- 🌟 - 🍴</li>
        {data.map((k, i) => {
          return <li>{k.full_name} - 🌟:{k.watchers_count}- 🍴:{k.forks_count}  </li>
        })}
      </ul>
      <div className='page_wrap'>
        <button className='last_page' onClick={() => { setPage(page - 1 <= 0 ? 1 : page - 1) }} >上一页</button>
        <button className='next_page' onClick={() => { setPage(page + 1) }}>下一页</button>
        <div className="page_count">{page}/{Math.floor(totalCount / count)}页 ({count}条/页)</div>
      </div>
    </div >
  );
}

export default App;
